package com.example.demo.controller;

import com.example.demo.enums.OrderStatusEnum;
import com.example.demo.pojo.Orders;
import com.example.demo.pojo.Product;
import com.example.demo.service.OrdersService;
import com.example.demo.service.ProductService;
import com.example.demo.util.LeeJSONResult;
import idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Date 2020-10-29 15:02
 * @Author: StarSea99
 */
@Controller
@RequestMapping
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrdersService ordersService;

    //获取产品列表
    @RequestMapping
    public String products(Map map) {
        List<Product> pList = productService.getProducts();
        map.put("pList", pList);
        return "index";
    }

    //首页显示，查询全部产品
    @RequestMapping("index")
    public String index(Map map) {
        List<Product> pList = productService.getProducts();
        map.put("pList", pList);
        return "index";
    }

    //进入购物车页面
    @RequestMapping(value = "/goConfirm")
    public String goConfirm(String productId, Map map) {
        Product p = productService.getProductById(productId);
        map.put("p", p);
        return "goConfirm";
    }

    //分段提交,保存订单
    @RequestMapping(value = "/createOrder")
    @ResponseBody
    public LeeJSONResult createOrder(Orders order) throws Exception {

        Product p = productService.getProductById(order.getProductId());

        Sid sid = new Sid();
        String orderId = sid.nextShort();//生成16位随机字符串

        order.setId(orderId);//设置id
        order.setOrderNum(orderId);//设置订单号
        order.setCreateTime(new Date());//设置创建时间
        order.setOrderAmount(String.valueOf(Float.valueOf(p.getPrice()) * order.getBuyCounts()));//实际支付金额
        order.setOrderStatus(OrderStatusEnum.WAIT_PAY.key);//订单状态

        ordersService.saveOrder(order);
        return LeeJSONResult.ok(orderId);
    }

    //分段提交,第二段
    @RequestMapping(value = "/goPay")
    public String goPay(String orderId, Map map) {
        //根据订单号查询订单
        Orders order = ordersService.getOrderById(orderId);
        //根据订单号查询产品
        Product p = productService.getProductById(order.getProductId());

        map.put("order", order);
        map.put("p", p);

        return "goPay";
    }
}
